import { defineStore } from 'pinia'
import { userLogin, testSystemExUserToken } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    userData: {},
    isLogin: false
  }),
  actions: {
    // 登录
    login(userInfo) {
      return new Promise((resolve, reject) => {
        userLogin(userInfo)
          .then((res) => {
            setToken(res.token)
            this.token = res.token
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        testSystemExUserToken()
          .then((res) => {
            if (res.code === 200) {
              this.userData = res.data.tvUser
              this.isLogin = true
              resolve(res.data.tvUser)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 退出系统
    logOut() {
      this.token = ''
      this.userData = []
      this.isLogin = false
      removeToken()
      resolve()
    }
  }
})

export default useUserStore
